package com.netty4.http.xml;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import static com.netty4.http.xml.HttpXmlRequestDecoder.sendError;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpUtil.isKeepAlive;

public class HttpXmlServerHandler extends SimpleChannelInboundHandler<HttpXmlRequest> {

    protected void  channelRead0(final ChannelHandlerContext channelHandlerContext, HttpXmlRequest httpXmlRequest) throws Exception {
        HttpRequest request = httpXmlRequest.getRequest();
        Order order = (Order) httpXmlRequest.getBody();
        dobusinessOrder(order);
        ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(new HttpXmlResponse(null, order));
        if(!isKeepAlive(request)){
            channelFuture.addListener(new GenericFutureListener<Future<? super Void>>() {
                public void operationComplete(Future<? super Void> future) throws Exception {
                    channelHandlerContext.close();
                }
            });
        }
    }

    private void dobusinessOrder(Order order){
        order.getCustomer().setFirstName("唐");
        order.getCustomer().setLastName("宇琳");
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.fireExceptionCaught(cause);
        if(ctx.channel().isActive()){
            sendError(ctx,INTERNAL_SERVER_ERROR);
        }
        ctx.close();
    }

}
